package cn.wolfcode.web.controller;

import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.common.web.anno.RequireLogin;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.util.UserUtil;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@RequestMapping("/order")
@Slf4j
public class OrderInfoController {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private IOrderInfoService orderInfoService;

    public static final Map<Long,Boolean> LOCAL_FLAG = new ConcurrentHashMap<>();


    @RequestMapping("/doSeckill")
    @RequireLogin
    public Result doSeckill(Long seckillId, int time, HttpServletRequest request){

        //本地标识
        Boolean aBoolean = LOCAL_FLAG.get(seckillId);
        if (aBoolean!=null && aBoolean){
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }

        //判断参数非空
        if (StringUtils.isEmpty(time)||StringUtils.isEmpty(seckillId)){
            throw new BusinessException(SeckillCodeMsg.PARAMETER_ERROR);
        }

        //判断商品是否为秒杀商品
        Object seckillByProductId = redisTemplate.opsForHash().get(SeckillRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time + ""), seckillId+"");
        if (seckillByProductId==null){
            throw new BusinessException(SeckillCodeMsg.SECKILL_PRODUCT_NOT_FOUND);
        }

        /*boolean isInTime = DateUtil.isLegalTime(, time);
        if (!isInTime){
            throw new BusinessException(SeckillCodeMsg.SECKILL_PRODUCT_NOT_FOUND);
        }*/


        //判断用户是否重复下单
        String token = request.getHeader("token");
        UserInfo user = UserUtil.getUser(redisTemplate, token);
        Boolean isExists = redisTemplate.opsForSet().isMember(SeckillRedisKey.SECKILL_ORDER_SET.getRealKey(time + ""), user.getPhone() + ":" + seckillId);
        if (isExists){
            throw new BusinessException(SeckillCodeMsg.REPEAT_SECKILL);
        }

        //判断库存是否足够
        //String s = redisTemplate.opsForValue().get(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time + ":" + seckillId));
        //SeckillProductVo seckillProductVo = seckillProductService.find(seckillId + "", time);
        int stockCount = seckillProductService.getStockCount(seckillId);
        if (stockCount<=0){
            LOCAL_FLAG.put(seckillId,true);
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }

        //减少缓存库存
        //Object o = redisTemplate.opsForHash().get(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(seckillId + ""), time);
        //JSON.parseObject(o,Integer.class)
        redisTemplate.opsForHash().increment(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time + ""),seckillId+"",-1);

        //发送MQ信息
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setSeckillId(seckillId);
        orderMessage.setTime(time);
        orderMessage.setUserPhone(user.getPhone());
        orderMessage.setToken(token);

        rocketMQTemplate.syncSend(MQConstant.ORDER_PEDDING_TOPIC,orderMessage);

        //调用业务方法
        //OrderInfo order = seckillProductService.doSeckill(time, seckillId, user.getPhone());

        //return Result.success(order.getOrderNo());


        return Result.success("正在抢购中");
    }

    @RequestMapping("/find")
    public Result<OrderInfo> find(String orderNo,HttpServletRequest request){
        if (StringUtils.isEmpty(orderNo)){
            throw new BusinessException(SeckillCodeMsg.PARAMETER_ERROR);
        }
        OrderInfo orderInfo = orderInfoService.find(orderNo);
        if (orderInfo==null){
            throw new BusinessException(SeckillCodeMsg.PARAMETER_ERROR);
        }
        String token = request.getHeader("token");
        UserInfo user = UserUtil.getUser(redisTemplate, token);
        if (!user.getPhone().equals(orderInfo.getUserId())){
            throw new BusinessException(SeckillCodeMsg.NOT_YOUR_LOGIN);
        }
        return Result.success(orderInfo);
    }
}
